import 'dart:async';

import 'package:aio/aio.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_footer.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_header.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/model/review_model.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/image_path_utils.dart';

// import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../../../http/bean/http_data.dart';
import '../../../http/bean/ywx_count.dart';
import '../../../http/model/todo_review_model.dart';
import '../../../manager/audit_manager.dart';
import '../works/public/content_list.dart';
import '../works/public/image/ui_image_upload.dart';

///待审核列表
class TodoReviewList extends StatefulWidget {
  ///审核类型
  YwxItem? item;

  ///是否刷新
  bool isRefresh = true;

  TodoReviewList(this.item, this.isRefresh);

  @override
  _TodoReviewListState createState() {
    return _TodoReviewListState();
  }
}

class _TodoReviewListState extends State<TodoReviewList> {
  _TodoReviewListPresenter presenter = _TodoReviewListPresenter();
  EasyRefreshController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    // print(
    //     '=====================================================================状态初始化');
    if (PlatformUtils.isWindows()) {
      presenter?.getTdogetlist(context, 0, () {
        setState(() {
          //resetLoadState 刷新完成。
          // _controller?.resetLoadState();
          IndicatorResult result = IndicatorResult.success; //成功
          _controller?.finishRefresh(result,
              true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
          _controller?.resetFooter();
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "todo_review_list.dart"); //fixme 不在审核详情页面。
    // print(
    //     '=====================================================================视图构建${presenter.datas?.length}');
    presenter.item = widget.item;
    if (widget.isRefresh) {
      AppUi.easyRefreshcallRefresh(_controller);
      widget.isRefresh = false;
    }
    return EasyRefresh(
      controller: _controller,
      // firstRefresh: true,
      refreshOnStart: true,
      header: EasyClassicalHeader(
        context,
        refreshText: AppStrings.of(context).refreshText,
        refreshReadyText: AppStrings.of(context).refreshReadyText,
        refreshingText: AppStrings.of(context).refreshingText,
        refreshedText: AppStrings.of(context).refreshedText,
        refreshFailedText: AppStrings.of(context).refreshFailedText,
      ),
      //footer 尾部，上拉加载更多布局
      footer: EasyClassicalFooter(
        context,
        loadText: AppStrings.of(context).loadText,
        loadReadyText: AppStrings.of(context).loadReadyText,
        loadingText: AppStrings.of(context).loadingText,
        loadedText: AppStrings.of(context).loadedText,
        loadFailedText: AppStrings.of(context).loadFailedText,
        noMoreText: AppStrings.of(context).noMoreText,
        infoText: AppStrings.of(context).infoText +
            '${DateTimeUtils.getDateTimeWithTime()}',
        showInfo: true,
      ),
      onRefresh: () async {
        Completer<void> completer = new Completer();
        presenter?.getTdogetlist(context, 0, () {
          completer.complete();
          if (mounted) {
            setState(() {
              //resetLoadState 刷新完成。
              // _controller?.resetLoadState();
              // completer.complete();
              // var isNoMore = presenter.isNoMore();
              // _controller?.finishRefresh(success: true, noMore: isNoMore);
              IndicatorResult result = IndicatorResult.success; //成功
              //result=IndicatorResult.fail;//失败
              _controller?.finishRefresh(result,
                  true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
              _controller?.resetFooter();
            });
          }
        });
        await completer.future;
      },
      onLoad: () async {
        var isNoMore = presenter.isNoMore(); //加载更多时，提前判断是否还有数据
        if (isNoMore) {
          //没有更多数据了
          if (mounted) {
            setState(() {
              // _controller?.finishLoad(success: true, noMore: isNoMore);
              IndicatorResult result = IndicatorResult.success; //加载成功
              if (isNoMore) {
                result = IndicatorResult.noMore; //没有更多数据了。
              }
              _controller?.finishLoad(result, true);
            });
          }
        } else {
          //还有更多数据
          Completer<void> completer = new Completer();
          presenter?.getTdogetlist(context, presenter.PageNo + 1, () {
            completer.complete();
            if (mounted) {
              setState(() {
                var isNoMore = presenter.isNoMore();
                // _controller?.finishLoad(success: true, noMore: isNoMore);
                IndicatorResult result = IndicatorResult.success; //加载成功
                if (isNoMore) {
                  result = IndicatorResult.noMore; //没有更多数据了。
                }
                _controller?.finishLoad(result, true);
              });
            }
          });
          await completer.future;
        }
      },
      child: CustomScrollView(slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return _item(context, index);
            },
            childCount: presenter.datas?.length ?? 0,
          ),
        ),
      ]),
      //slivers 主布局
    );
  }

  Widget _item(BuildContext context, int index) {
    YwxItemNotice data = presenter.datas![index];
    List<Widget> children = [];
    //第一行
    var _str = " ${index + 1}";
    if (StringUtils.isNotEmpty(data.ReviewTypeName)) {
      _str = " ${index + 1}." + data.ReviewTypeName!;
    }
    children.add(Row(
      children: [
        Image.asset(
          ImagePathUtils.getPathWithImageEntry("ic_entry.png"),
          width: 14,
        ),
        Listener(
          onPointerUp: (event) {
            if (StringUtils.isNotEmpty(data.ReviewTypeName)) {
              TextUtils.copyText(data.ReviewTypeName); //文本复制
            }
          },
          child: Text(
            _str, //ReviewTypeName
            style: AppStyle.textStyleWithEntryTitle(),
          ),
        ),
        Expanded(
          child: Text(''),
        ),
        Text(
          "  " + data.YwxName!,
          style: AppStyle.textStyleWithEntryBlue(),
        ),
      ],
    ));
    //中间内容
    children.add(ContentList.todo(context, data));
    //最后一行
    var lastRow = Row(
      children: [
        Expanded(
          child: Text(''),
        ),
        Text(
          "  " + data.getOrderOrStatusName()!,
          style: AppStyle.textStyleWithEntryTitle(),
        ),
        AppUi.getSizeBox(width: 24),
        MaterialButton(
          onPressed: () {
            //fixme 详情跳转
            data.goWorksDetails(context)?.then((value) {
              //print("页面返回");
              UiImageUpLoad.clear(); //图片清除
              if (value != null) {
                AppUi.easyRefreshcallRefresh(_controller); //重新刷新。
              }
            });
          },
          shape: RoundedRectangleBorder(
              side: BorderSide.merge(
                  BorderSide(color: Colors.blueAccent, width: 1),
                  BorderSide.none),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Text(
            data.getShenhe(context),
            style: AppStyle.textStyleWithEntryTitleBlue(),
          ),
        )
      ],
    );
    children.add(Container(
      child: lastRow,
      height: 35,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
    ));
    var column = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
    return UiCard.build(context, column);
  }
}

class _TodoReviewListPresenter {
  ///审核类型
  YwxItem? item = null;

  ///当前页码，从0开始
  int PageNo = 0;

  //总数据个数
  int TotalNum = 0;

  List<YwxItemNotice>? datas;

  ///判断是否没有更多数据了
  bool isNoMore() {
    //return true;
    if (datas != null && datas!.length > 0) {
      if (datas!.length >= TotalNum) {
        return true;
      }
    }
    return false;
  }

  ///获取待审核类型
  getTdogetlist(
      BuildContext context, int PageNo, ResponseCallbackWithVoid response) {
    // print(
    //     '=====================================================================请求开始 PageNo:$PageNo\t${isNoMore()}');
    var PageSize = "30";
    if (YwxCount.allNum > 0) {
      PageSize = YwxCount.allNum.toString();
    }
    TodoReviewModel.getTdogetlist(
      context,
      false,
      ReviewType: item?.ReviewType,
      // PageNo: PageNo.toString(),
      PageNo: "0",
      PageSize: PageSize,
    )?.then((value) {
      //print("==============================================================返回");
      if (value == null) {
        AppDialog.showDialogWithInfo(context,
            content: AppStrings.of(context).net_error_02); //服务器连接失败
      } else {
        if (value.isSuccessForCode()) {
          if (value.isSuccessForData()) {
            TotalNum = value.TotalNum;
            if (PageNo == 0) {
              datas = value.Data;
            } else {
              datas!.addAll(value.Data!);
            }
            this.PageNo = PageNo;
            // print(
            //     '==============================================================个数：${datas?.length}\t${TotalNum}');
          } else {
            if (PageNo == 0) {
              datas?.clear();
            }
            if (PageNo == 0 || !isNoMore()) {
              //数据为空
              AppDialog.showDialogWithInfo(context,
                  content: AppStrings.of(context).dataEmpty);
            }
          }
        } else {
          AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
        }
      }
      response?.call();
    });
  }
}
